package com.study.talk.module.netty.handler;

import com.study.talk.common.util.SessionUtil;
import com.study.talk.module.entity.GroupInfo;
import com.study.talk.module.entity.GroupUserInfo;
import com.study.talk.module.entity.UserInfo;
import com.study.talk.module.netty.message.Attributes;
import com.study.talk.module.netty.message.Session;
import com.study.talk.module.netty.message.request.AcceptJoinGroupRequest;
import com.study.talk.module.netty.message.response.AcceptJoinGroupResponse;
import com.study.talk.module.netty.message.response.GroupMessageResponse;
import com.study.talk.module.service.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 同意加入群聊消息处理
 */

@Component
@Slf4j
@ChannelHandler.Sharable
public class AcceptJoinGroupRequestHandler extends SimpleChannelInboundHandler<AcceptJoinGroupRequest> {

    @Resource
    private GroupInfoService groupInfoService;

    @Resource
    private GroupUserInfoService groupUserInfoService;

    @Resource
    private UserService userService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private ApplyJoinGroupRecordService applyJoinGroupRecordService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AcceptJoinGroupRequest msg) throws Exception {
        log.info("同意用户加入群聊事件,{}",msg);

        AcceptJoinGroupResponse acceptJoinGroupResponse = new AcceptJoinGroupResponse();
        acceptJoinGroupResponse.setGroupId(msg.getGroupId());
        acceptJoinGroupResponse.setSuccess(msg.getAccept());
        acceptJoinGroupResponse.setDateTime(msg.getDateTime());
        Session session = ctx.channel().attr(Attributes.SESSION).get();
        GroupInfo groupInfo = groupInfoService.getById(msg.getGroupId());
        acceptJoinGroupResponse.setGroupName(groupInfo.getName());

        //移除申请记录
        applyJoinGroupRecordService.removeRecord(groupInfo.getId(),msg.getUserId());

        //群主同意入群
        if (acceptJoinGroupResponse.getSuccess() && session.getUserId().equals(groupInfo.getMainUser())){
            groupUserInfoService.addMember(groupInfo.getId(),msg.getUserId());
            UserInfo userInfo = userInfoService.getById(msg.getUserId());
            groupInfoService.sendAcceptJoinGroupMsg(groupInfo,userInfo);
        }

        userService.sendMessage(msg.getUserId(),acceptJoinGroupResponse);
    }
}
